<template>
  <div>
    <div
      class="topSearch"
      style="margin-bottom: 10px; display: flex; justify-content: space-between"
    >
      <div
        style="
          display: flex;
          align-items: center;
          width: 760px;
          justify-content: space-between;
        "
      >
        <span style="text-align: center; margin-left: 20px"
          >品牌方：
          <el-select
            v-model="params.systemType"
            placeholder="请按品牌方搜索"
            size="small"
            style="width: 200px"
          >
            <el-option
              :value="item.id"
              :label="item.systemName"
              :key="item.id"
              v-for="item in systemList"
            ></el-option>
          </el-select>
        </span>
        <div>
          <span
            >所属仓库：
            <el-select
              size="small"
              style="width: 250px"
              v-model="params.area"
              clearable
            >
              <el-option
                v-for="item in warehouseList"
                :label="item.areaName"
                :value="item.area"
                :key="item.area"
              ></el-option> </el-select
          ></span>
          <!-- <span style="margin-left: 15px"
          >门店名称：<el-input
            size="small"
            style="width: 250px"
            v-model="params.storeName"
            clearable
          ></el-input
        ></span> -->
          <span style="margin-left: 15px">
            <el-button size="small" type="primary" @click="_search"
              >搜 索</el-button
            >
            <el-button size="small" type="info" @click="_reset"
              >重 置</el-button
            >
          </span>
        </div>
      </div>
      <div>
        <el-button size="small" type="primary" @click="_add"
          >新增其他费用
        </el-button>
        <el-button type="primary" size="small" @click="getData('download')"
          ><i class="el-icon-download"></i>财务其他费用表下载
        </el-button>
      </div>
    </div>
    <div class="centerTable">
      <el-table
        :data="multipleData"
        height="calc(100vh - 350px)"
        :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
        :headerCellStyle="{
          textAlign: 'center',
          fontWeight: 400,
          background: '#66b1ff',
          color: 'white',
        }"
      >
        <el-table-column prop="id" label="ID"></el-table-column>

        <el-table-column
          v-for="col in editableColumns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          :width="col.label == '金额' ? '100px' : '150px'"
        >
          <template v-slot:default="scope">
            <!-- {{ col.prop }} -->
            <el-input
              v-if="scope.row.isEditing[col.prop]"
              v-model="scope.row[col.prop]"
              @blur="blurEvent(scope.row, scope.$index, col.prop)"
              v-focus
            ></el-input>
            <div v-else-if="col.prop === 'addImgList'">
              <div style="display: flex">
                <el-image
                  v-for="(item, index) in scope.row.addImgList"
                  :key="index"
                  :src="host + item"
                  :preview-src-list="
                    scope.row.addImgList.map((img) => host + img)
                  "
                  class="img-item"
                  fit="cover"
                >
                </el-image>
              </div>
            </div>
            <p
              v-else
              @click="cellClick(scope.row, col.prop)"
              style="min-width: 100px; line-height: 50px; min-height: 50px"
            >
              {{ scope.row[col.prop] || ' ' }}
            </p>
          </template>
        </el-table-column>
        <el-table-column prop="a" label="操作">
          <template v-slot:default="scope">
            <el-link
              style="
                color: #66b1ff;
                text-decoration: underline;
                margin-right: 10px;
              "
              @click="_edit(scope.row)"
              >编 辑
            </el-link>
            <el-link
                v-if="userName=='曹紫芳'"
              style="
                color: #ce0e0f;
                text-decoration: underline;
                margin-right: 10px;
              "
              @click="_delete(scope.row)"
              >删 除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="padding: 20px 0"
        align="right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[20, 30, 40, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <div>
      <el-dialog
        :visible.sync="dialogAdd"
        :title="title"
        top="10px"
        height="calc(100vh - 350px)"
        style="overflow-y: auto"
        width="50%"
      >
        <div>
          <el-row>
            <el-col :span="12" style="margin-bottom: 5px">
              <div style="width: 80px; white-space: nowrap">
                仓库采购费用备注:
              </div>
              <el-input
                size="small"
                style="width: 280px"
                type="textarea"
                v-model="data.whProcureRemark"
              ></el-input>
            </el-col>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">仓库采购费用：</div>
              <el-input-number
                v-model="data.whProcureMoney"
                :min="0"
                size="small"
                style="width: 200px"
                @change="changeNum('secondVisit', $event)"
              ></el-input-number>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">
                仓库采购未入成本备注：
              </div>
              <el-input
                size="small"
                style="width: 280px"
                type="textarea"
                v-model="data.whProcureNotRemark"
              ></el-input>
            </el-col>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">
                仓库采购未入成本:
              </div>
              <el-input-number
                v-model="data.whProcureNotMoney"
                :min="0"
                size="small"
                style="width: 200px"
                @change="changeNum('secondVisit', $event)"
              ></el-input-number>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">生活费用说明:</div>
              <el-input
                size="small"
                style="width: 280px"
                type="textarea"
                v-model="data.livingRemark"
              ></el-input>
            </el-col>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">生活费用:</div>
              <el-input-number
                v-model="data.livingMoney"
                :min="0"
                size="small"
                style="width: 200px"
                @change="changeNum('secondVisit', $event)"
              ></el-input-number>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">叉车费用说明:</div>
              <el-input
                size="small"
                style="width: 280px"
                type="textarea"
                v-model="data.forkliftRemark"
              ></el-input>
            </el-col>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">叉车费用:</div>
              <el-input-number
                v-model="data.forkliftMoney"
                :min="0"
                size="small"
                style="width: 200px"
                @change="changeNum('secondVisit', $event)"
              ></el-input-number>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">
                快递到三月以前店铺处理售后费用说明:
              </div>
              <el-input
                size="small"
                style="width: 280px"
                type="textarea"
                v-model="data.storeAfterRemark"
              ></el-input>
            </el-col>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">
                快递到三月以前店铺处理售后费用:
              </div>
              <el-input-number
                v-model="data.storeAfterMoney"
                :min="0"
                size="small"
                style="width: 200px"
                @change="changeNum('secondVisit', $event)"
              ></el-input-number>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">
                请临时工费用说明:
              </div>
              <el-input
                size="small"
                style="width: 280px"
                type="textarea"
                v-model="data.temporaryWorkerRemark"
              ></el-input>
            </el-col>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">请临时工费用:</div>
              <el-input-number
                v-model="data.temporaryWorkerMoney"
                :min="0"
                size="small"
                style="width: 200px"
                @change="changeNum('secondVisit', $event)"
              ></el-input-number>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">
                货架回仓库货拉拉费用说明:
              </div>
              <el-input
                size="small"
                style="width: 280px"
                type="textarea"
                v-model="data.returnHuolala"
              ></el-input>
            </el-col>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">
                货架回仓库货拉拉费用:
              </div>
              <el-input-number
                v-model="data.returnHuolalaMoney"
                :min="0"
                size="small"
                style="width: 200px"
                @change="changeNum('secondVisit', $event)"
              ></el-input-number>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div style="width: 50px; white-space: nowrap">仓库月租金:</div>
              <el-input-number
                v-model="data.whMonthMoney"
                :min="0"
                size="small"
                style="width: 200px"
                @change="changeNum('secondVisit', $event)"
              ></el-input-number>
            </el-col>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">仓库：</div>
              <el-select
                clearable
                size="small"
                v-model="data.area"
                :disabled="disabled"
                style="width: 45%"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in warehouseList"
                  :key="item.area"
                  :label="item.areaName"
                  :value="item.area"
                />
              </el-select>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">
                湖南办公室费用说明:
              </div>
              <el-input
                size="small"
                style="width: 280px"
                type="textarea"
                v-model="data.hunanOfficeRemark"
              ></el-input>
            </el-col>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">
                湖南办公室费用:
              </div>
              <el-input-number
                v-model="data.hunanOfficeMoney"
                :min="0"
                size="small"
                style="width: 200px"
                @change="changeNum('secondVisit', $event)"
              ></el-input-number>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">端头费用说明:</div>
              <el-input
                size="small"
                style="width: 280px"
                v-model="data.tipRemark"
                type="textarea"
              ></el-input>
            </el-col>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">端头费用:</div>
              <el-input-number
                v-model="data.tipMoney"
                :min="0"
                size="small"
                style="width: 200px"
                @change="changeNum('secondVisit', $event)"
              ></el-input-number>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">品牌方</div>
              <el-select
                v-model="data.systemType"
                placeholder="请按品牌方搜索"
                size="small"
                style="width: 200px"
              >
                <el-option
                  :value="item.id"
                  :label="item.systemName"
                  :key="item.id"
                  v-for="item in systemList"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="12">
              <div style="width: 80px; white-space: nowrap">凭证：</div>
              <div>
                <span style="color: gray; font-size: 12px; white-space: nowrap"
                  >(粘贴复制即可上传图片)</span
                >
                <div class="div" style="display: flex; align-items: center">
                  <div
                    v-for="(v, i) in changeVouchers"
                    style="
                      display: flex;
                      align-items: center;
                      margin-right: 10px;
                    "
                    :key="i"
                  >
                    <el-image
                      v-if="v"
                      :key="i"
                      style="width: 50px; height: 50px"
                      ref="preview"
                      :src="host + v"
                      :preview-src-list="[host + v]"
                    >
                    </el-image>
                    <!-- v-show="!editDetails" -->
                    <div @click="deleteImgVouchers(i)">
                      <el-icon name="delete"></el-icon>
                    </div>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row v-if="title == '编辑'">
            <el-col :span="12">
              <span style="width: 80px">运费:</span>
              <el-input-number
                v-model="data.freight"
                :min="0"
                size="small"
                style="width: 200px"
                @change="changeNum('secondVisit', $event)"
              ></el-input-number>
            </el-col>
          </el-row>
        </div>
        <span slot="footer">
          <el-button @click="dialogAdd = false">取 消</el-button>
          <el-button type="primary" @click="_submit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import {
  localStorageAsync,
  downloadReportWithImage,
  DataDictionary,
} from '@/utils/public'
// import ExcelJS from 'exceljs'
import axios from 'axios'
import quinn from "../../utils/quinn";
// import { Message } from 'element-ui'
const dataDictionary = new DataDictionary()
export default {
  name: 'otherExpenses',
  data() {
    return {
      dialogAdd: false,
      disabled: false,
      changeVouchers: [],
      systemList: [],
      title: '',
      date: '',
      areaId: '',
      num: 0,
      currentPage: 1,
      total: 0,
      host: this.$imgHost,
      userName:"",
      warehouseList: [],
      editableColumns: [
        { prop: 'systemType', label: '所属品牌' },
        { prop: 'whProcureRemark', label: '仓库采购费用' },
        { prop: 'whProcureMoney', label: '金额' },
        { prop: 'whProcureNotRemark', label: '仓库采购未入成本费用' },
        { prop: 'whProcureNotMoney', label: '金额' },
        {
          prop: 'livingRemark',
          label: '生活费用（房租，吃饭）出差费用（车票、住房）',
        },
        { prop: 'livingMoney', label: '金额' },
        {
          prop: 'addImgList',
          label: '凭证截图',
        },
        { prop: 'forkliftRemark', label: '叉车费用，货拉拉到零食很忙公司' },
        { prop: 'forkliftMoney', label: '金额' },
        { prop: 'storeAfterRemark', label: '快递到3月份以前店铺处理售后费用' },
        { prop: 'storeAfterMoney', label: '金额' },
        { prop: 'temporaryWorkerRemark', label: '请临时工费用' },
        { prop: 'temporaryWorkerMoney', label: '金额' },
        { prop: 'returnHuolala', label: '货架回仓库货拉金额拉费用' },
        { prop: 'returnHuolalaMoney', label: '金额' },
        { prop: 'whMonthMoney', label: '仓库月租金' },
        { prop: 'hunanOfficeRemark', label: '湖南办公室费用' },
        { prop: 'hunanOfficeMoney', label: '金额' },
        { prop: 'tipRemark', label: '端头费用' },
        { prop: 'tipMoney', label: '金额' },
        { prop: 'freight', label: '运费' },
      ],
      data: {},
      editId: '',
      params: {
        storeName: '',
        area: '',
        systemType: '',
        pageNumber: 1,
        pageSize: 20,
      },
      orderImg: [],
      productData: [],
      multipleData: [],
    }
  },
  computed: {
    headers() {
      const token = this.$quinn.getStorage('token')
      return {
        token,
      }
    },
  },
  directives: {
    focus: {
      inserted: function (el) {
        el.querySelector('input').focus()
      },
    },
  },
  created() {
    this.getSystemType()
    this.areaList()
    this.getData()
    document.addEventListener('paste', this.handlePaste)
    const {userName = []} = quinn.getStorage("userData") || {};
    this.userName = userName
  },
  methods: {
    getSystemType() {
      // 获取品牌方类型
      this.$api.orderGetSystemTypeVo().then((res) => {
        this.systemList = res
        console.log('res', res)
      })
    },
    /**
     * 方法说明 处理粘贴
     * author: iceyhu
     * description:
     * @param
     * @return
     * @createTime: DATE_TIME
     */
    handlePaste(event) {
      // 只能编辑损坏明细
      // if (this.editDetails) return
      // !this.editVouchers &&
      if (!this.dialogAdd) return
      const clipboardData = event.clipboardData || window.clipboardData
      // console.log('clipboardData', clipboardData)
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i]
          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile()
            if (file) {
              this.uploadImage(file) // 处理文件上传逻辑
            }
          } else {
            this.$message.error('请拷贝图片!')
            break
          }
        }
      }
    },
    async _submit() {
      try {
        const apiMap = {
          新增: this.$api.financeAddOtherFee,
          编辑: this.$api.financeUpdateOtherFee,
        }

        const apiFunc = apiMap[this.title]
        if (!apiFunc) return
        const subData = {
          ...this.data,
          addImgList: this.changeVouchers,
        }
        if (this.title == '编辑') subData.id = this.editId
        const resDate = await apiFunc(subData)
        if (resDate == 1) {
          this.$message.success(`${this.title}成功！`)
          this.dialogAdd = false
          this.getData()
        }
      } catch (err) {
        console.error('接口请求出错：', err)
        this.$message.error('操作失败，请稍后重试')
      }
    },
    /**
     * 方法说明 上传图片
     * author: iceyhu
     * description:
     * @param
     * @return
     * @createTime: DATE_TIME
     */
    uploadImage(imageFile) {
      console.log('imageFile', imageFile)
      const formData = new FormData()
      formData.append('file', imageFile)
      axios
        .post(`${this.$apiHost}/common/fileImgUrl`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            token: window.$quinn.getStorage('token'),
          },
        })
        .then((response) => {
          if (this.dialogAdd) {
            console.log('dialogAdd', this.dialogAdd)
            this.changeVouchers.push(response.data.result[0])
          }
          // if (this.editVouchers) {
          //   // 上传修改凭证
          //   this.editImg.push(response.data.result[0])
          //   // this.editImgList.push('https://' + response.data.result[0]);
          // }
        })
        .catch((error) => {})
    },
    deleteImgVouchers(i) {
      this.changeVouchers.splice(i, 1)
    },
    blurEvent(row, index, column) {
      row.isEditing[column] = false
      const payload = {
        id: row.id,
        [column]: row[column],
      }
      this.$api.financeUpdateOtherFee(payload).then((res) => {
        if (res == 1) {
          this.$message.success('修改成功！')
          this.getData()
        }
      })
    },
    cellClick(row, column) {
      console.log(row, column)
      //input编辑
      Object.keys(row.isEditing).forEach((key) => {
        row.isEditing[key] = false
      })
      // 取消
      row.isEditing[column] = true
    },
    handleSizeChange(val) {
      this.params.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.params.pageNumber = val
      this.getData()
    },
    _search() {
      this.params.pageNumber = 1
      this.getData()
    },
    _reset() {
      this.params = this.$options.data().params
      this.getData()
    },
    /**
     * 方法说明
     * author: iceyhu
     * description:
     * @param{String} dataPurpose 获取数据用途 [default||download]
     * @return
     * @createTime: DATE_TIME
     */
    async getData(dataPurpose = 'default') {
      if (dataPurpose == 'default') {
        const result = await localStorageAsync.removeItem('download')
        if (result == 'success') {
          this.$api.financeGetOtherList(this.params).then((res) => {
            res.data.forEach((el) => {
              // el.systemType = dataDictionary.get(el.systemType) // 处理品牌方字段
              // console.log('el.systemType', el.systemType)
              el.isEditing = {}
              this.editableColumns.forEach((col) => {
                el.isEditing[col.prop] = false
              })
            })
            this.multipleData = res.data
            this.total = res.total
          })
        }
      } else if (dataPurpose == 'download') {
        const result = await localStorageAsync.setItem('download', true)
        if (result == 'success') {
          this.params.pageNumber = 1
          this.params.pageSize = 10000
          this.$api.financeGetOtherList(this.params).then((res) => {
            // console.log('getZymCashRegisterList', res)
            res.data.forEach((el) => {
              el.systemType = dataDictionary.get(el.systemType) // 处理品牌方字段
              // el.isEditing = {}
              // this.editableColumns.forEach((col) => {
              //   el.isEditing[col.prop] = false
              // })
            })
            // console.log('el.systemType', el.systemType)
            this.downloadOtherExpenses(res.data)
          })
        }
      }
    },
    /**
     * 方法说明
     * author: iceyhu
     * description: 下载其他费用表
     * @param{Array} tableData 需要被下载的全部表格数据
     * @return
     * @createTime: DATE_TIME
     */
    downloadOtherExpenses(tableData) {
      if (!tableData.length) return this.$message.warning('暂无可下载数据')
      const headers = [
        '所属品牌',
        '仓库采购费用',
        '金额',
        '仓库采购未入成本费用',
        '金额',
        '生活费用(房租，吃饭)出差费用（车票、住房）',
        '金额',
        '凭证截图',
        '叉车费用，货拉拉到零食很忙公司',
        '金额',
        '快递到3月份以前店铺处理售后费用',
        '金额',
        '请临时工费用',
        '金额',
        '货架回仓库货拉金额费用',
        '金额',
        '仓库月租金',
        '湖南办公室费用',
        '金额',
        '端头费用',
        '金额',
      ]
      downloadReportWithImage(headers, tableData, {
        fileName: '其他费用表',
        fileSort: 'otherReport',
      })
    },
    // getData() {
    //   const params = this.params
    //   this.$api.financeGetOtherList(params).then((res) => {
    //     // console.log(res)
    //     res.data.map((el) => {
    //       el.isEditing = {}
    //       this.editableColumns.forEach((col) => {
    //         el.isEditing[col.prop] = false
    //       })
    //     })
    //     this.multipleData = res.data
    //     this.total = res.total
    //   })
    // },
    _add() {
      this.dialogAdd = true
      this.title = '新增'
      this.data = []
    },
    areaList() {
      this.$api.areaLedgerAreaList().then((res) => {
        this.warehouseList = res
      })
    },
    changeNum(field, val) {
      if (!val) {
        this.$set(this.data, field, 0)
      }
    },
    _delete(e) {
      const data = {
        id: e.id,
      }
      this.$confirm('确认删除？')
        .then((_) => {
          this.$api.financeDeleteOtherFee(data).then((res) => {
            if (res == 1) {
              this.$message.success('删除成功！')
              this.getData()
            }
          })
        })
        .catch((_) => {
          return
        })
    },
    _edit(a) {
      console.log('row', a)
      const data = JSON.parse(JSON.stringify(a))
      this.dialogAdd = true
      this.editId = data.id
      this.title = '编辑'
      this.data = data
      this.changeVouchers = data.addImgList || [] // 回显凭证
    },
  },
}
</script>

<style scoped lang="less">
.el-col .el-col-12 {
  display: block !important;
}
.el-row {
  margin-bottom: 20px;

  span {
    display: inline-block;
    width: 90px;
  }
}
</style>
